package com.example.baseapp.business.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.baseapp.common.Result;
import com.example.baseapp.business.dto.req.UserReq;
import com.example.baseapp.business.entity.User;
import com.example.baseapp.business.interfaces.NotConflictUser;
import com.example.baseapp.business.interfaces.UniqueUser;
import com.example.baseapp.business.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;

/**
 * 用户表(User)表控制层
 *
 * @author zhanglei
 * @since 2022-03-23 15:26:27
 */
@Slf4j
@RestController
@RequestMapping("user")
@Validated
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @GetMapping("hello")
    public Result hello() {
        return Result.success("HELLO WORLD ！");
    }

    @GetMapping("anotherHello")
    public String antherHello() {
        return "Another HELLO WORLD !";
    }

    /**
     * 测试全局异常是否正常
     */
    @GetMapping("exception")
    public void exception() {
        throw new RuntimeException("自定义异常");
    }

    @PostMapping("user")
    public User createUser(@UniqueUser @Valid @RequestBody UserReq userReq) {
        Date date = new Date();
        User user = new User().setName(userReq.getName()).setEmail(userReq.getEmail()).setTel(userReq.getTel())
                .setPasswordDigest(userReq.getPassword()).setCreatedAt(date).setUpdatedAt(date).setStatus("S");
        userMapper.insert(user);
        return user;
    }
    @PutMapping("update")
    public User upDateUser(@NotConflictUser  @Valid @RequestBody UserReq userReq) {

        LambdaUpdateWrapper lambdaUpdateWrapper =  new LambdaUpdateWrapper<User>()
                .set(StringUtils.hasText(userReq.getEmail()),User::getEmail,userReq.getEmail())
                .set(StringUtils.hasText(userReq.getTel()),User::getTel,userReq.getTel())
                .set(StringUtils.hasText(userReq.getPassword()),User::getPasswordDigest,userReq.getPassword())
                .set(StringUtils.hasText(userReq.getName()),User::getName,userReq.getName())
                .eq(User::getId,userReq.getId());
        User user = new User();
        userMapper.update(user,lambdaUpdateWrapper);
        return userReq;
    }

}